/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccstore.servlet;

import it.unitn.science.matr155863_148346_145963.bccstore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccstore.items.Category;
import it.unitn.science.matr155863_148346_145963.bccstore.items.Image;
import it.unitn.science.matr155863_148346_145963.bccstore.items.Product;
import it.unitn.science.matr155863_148346_145963.bccstore.items.ProductDetailsValidator;
import it.unitn.science.matr155863_148346_145963.bccstore.items.UM;
import it.unitn.science.matr155863_148346_145963.bccstore.items.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import org.apache.log4j.Logger;

/**
 *
 * @author berto
 */
public class AddProductSRV extends HttpServlet {

    private DBManager db;
    private String srcCategory;
    ArrayList<Image> listImage;
    //private String srcImage;
    private String srcUm;
    private static Logger log = Logger.getLogger(AddProductSRV.class);
    
    @Override
    public void init() throws UnavailableException{
            db=(DBManager)super.getServletContext().getAttribute("db_manager");
            
            ArrayList<Category> listCat=db.getCategories();
            srcCategory="<select name=\""+Product.CATEGORY+"\">";
            for(Category c:listCat){
                srcCategory=srcCategory+"<option value=\""+c.getId()+"\" >"+c.getName()+"</option>";
            }
            srcCategory=srcCategory+"</select>";
            
            listImage=db.getImages();
            /*
            srcImage="<select name=\""+Product.IMAGE+"\">";
            for(String s:listImage){
                srcImage=srcImage+"<option value=\""+s+"\" >"
                        + "<img src=\""+s+"\" />"
                        +"</option>";
            }
            srcImage=srcImage+"</select>";
            */
            
            ArrayList<UM> listUm=db.getUMs();
            srcUm="<select name=\""+Product.UM+"\">";
            for(UM um:listUm){
                srcUm=srcUm+"<option value=\""+um.getId()+"\" >"+um.getName()+"</option>";
            }
            srcUm=srcUm+"</select>";
    }
    
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Product product=null;
        String errorOn=null;
        String address=null;
        try {
            //Controllo se ho cliccato il bottone per aggiungere il prodotto
            if(request.getParameter("add_product")!=null){
                try{
                    product=ProductDetailsValidator.createProduct(request,db);
                    User user=(User) request.getSession().getAttribute("user");
                    product.setSellerId(user.getId());
                    Integer id=db.addProduct(product);
                    product.setId(id);
                }catch(Exception ex){
                    //Error diuring operation
                    product=null;
                    errorOn=ex.getMessage();
                }
            }
            if(product==null){
                showForm(request,response,out,errorOn);
            }else{
                out.print("<h2>The product added</h2>");
                address="/contents/user/ShowProductDetails?id="+product.getId();
            }
        }catch(Exception ex){
            address="/contents/public/errorPage.html";
        } finally {    
            if(address!=null){
                RequestDispatcher dispatcher=request.getRequestDispatcher(address);
                dispatcher.include(request, response);
            }
        }
    }

    private void showForm(HttpServletRequest request,HttpServletResponse response,PrintWriter out ,String errorOn) {
            out.println("<h1>Add product:</h1>");
            if(errorOn!=null){
                out.println("<p>Unable to add the product."
                      + "\nYou have an error on field: \""
                        +errorOn+"\"</p>");
            }
            String name=request.getParameter(Product.NAME);
            if(name==null){
                name="";
            }
            String price=request.getParameter(Product.PRICE);
            if(price==null){
                price="";
            }
            String quantity=request.getParameter(Product.QUANTITY);
            if(quantity==null){
                quantity="";
            }
            String description=request.getParameter(Product.DESCRIPTION);
            if(description==null){
                description="";
            }
            String srcImage="<select name=\""+Product.IMAGE+"\">";
            for(Image i:listImage){
                /*
                 srcImage=srcImage+"<option value=\""+i.getId()+"\" >"
                        + "<img src=\""+request.getContextPath()+"/images/products/"+i.getName()+"\" />"
                        +"</option>";
                 */
                 srcImage=srcImage+"<option value=\""+i.getId()+"\">"+i.getName()
                        +"</option>";
            }
            srcImage=srcImage+"</select>";
            out.println(
                      "<form name=\"add_product\" method=\"post\""
                    + " action=\""+response.encodeURL(request.getRequestURL().toString())+"\">"
                        + "<table>"
                            + "<tr>"
                                + "<td>Name:</td>"
                                + "<td>"
                                    +"<input type=\"text\" "
                                    + "name=\""+Product.NAME+"\" "
                                    + "value=\""+name+"\""
                                    + "/>" 
                                +"</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td>Price:</td>"
                                + "<td>"
                                    +"<input type=\"text\" "
                                    + "name=\""+Product.PRICE+"\" "
                                    + "value=\""+price+"\""
                                    + "/>"
                                    + " euro ;" 
                                +"</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td>Quantity:</td>"
                                + "<td>"
                                    +"<input type=\"text\" "
                                    + "name=\""+Product.QUANTITY+"\" "
                                    + "value=\""+quantity+"\""
                                    + "/>" 
                                    + srcUm
                                +"</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td>Image:</td>"
                                + "<td>"
                                    + srcImage
                                +"</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td>Description:</td>"
                                + "<td>"
                                    +"<input type=\"text\" "
                                    + "name=\""+Product.DESCRIPTION+"\" "
                                    + "value=\""+description+"\""
                                    + "/>" 
                                +"</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td>Category:</td>"
                                + "<td>"
                                + srcCategory
                                +"</td>"
                            + "</tr>"
                            + "<tr>"
                                + "<td>"
                                    +"<input type=\"reset\" "
                                    + "name=\"reset\" "  
                                    + "value=\"Reset\""
                                    + "/>" 
                                +"</td>"
                                + "<td>"
                                    +"<input type=\"submit\" "
                                    + "name=\"add_product\""
                                    + "value=\"Add\""
                                    + "/>"  
                                +"</td>"
                            + "</tr>"
                        + "</table>"
                    + "</form>"
                    );
    }
    
    
    
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
